package com.io.smartappframe.mvc.activity

import android.graphics.ImageFormat
import android.graphics.Point
import android.hardware.Camera
import android.os.Bundle
import android.util.DisplayMetrics
import android.view.Display
import android.view.SurfaceHolder
import android.view.View
import com.io.base.mvc.BaseActivityMVC
import com.io.commonlib.helper.LogHelper
import com.io.smartappframe.R
import com.io.smartappframe.databinding.ActivityCameraBinding
import okhttp3.internal.wait

/**
 * Description:实现Camera的图像预览
 * 2021-06-07 10:22
 * @author LiuMin
 */
class CameraActivity : BaseActivityMVC<ActivityCameraBinding>(), View.OnClickListener,
    SurfaceHolder.Callback {

    private var camera: Camera? = null

    override fun initView(savedInstanceState: Bundle?): ActivityCameraBinding {
        return ActivityCameraBinding.inflate(layoutInflater)
    }

    override fun initData(savedInstanceState: Bundle?) {
        mViewBinding.header.tvTitle.setText("预览Camera图像")
        mViewBinding.header.ivToolbarBack.setOnClickListener(this)
        mViewBinding.btnStart.setOnClickListener(this)
        mViewBinding.btnStop.setOnClickListener(this)
        mViewBinding.surfaceView.holder.addCallback(this)
    }

    override fun onClick(v: View?) {
        v?.let {
            if (it.id == R.id.iv_toolbar_back) {
                finish()
            } else if (it.id == R.id.btnStart) {
                start()
            } else if (it.id == R.id.btnStop) {
                camera?.stopPreview()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        camera?.release()
    }

    //region 实现SurfaceHolder.Callback接口
    override fun surfaceCreated(holder: SurfaceHolder) {
        LogHelper.d(TAG, "surfaceCreated--------------------")
    }

    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
        LogHelper.d(TAG, "surfaceChanged--------------------")
    }

    override fun surfaceDestroyed(holder: SurfaceHolder) {
        LogHelper.d(TAG, "surfaceDestroyed--------------------")
    }
    //endregion

    //region 私有方法
    //开始预览
    private fun start() {
        camera = Camera.open(0)
        camera?.let {
            val parameters = it.parameters
            parameters?.let { it0 ->
                parameters.pictureFormat = ImageFormat.JPEG //设置图片属性
                //设置相机对焦模式，FOCUS_MODE_CONTINUOUS_PICTURE使用连续对焦
                parameters.focusMode = Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE
                //界面属性不一样，所以设置宽高处理界面异常拉伸
                val display = windowManager.defaultDisplay
                var height = display.height
                var width = display.width
                //val preSize = getSuitableSize(width, height, parameters)
                val point = getRealScreenMetrics()
                val cameraSize = getBestCameraResolution(parameters, point)
                cameraSize?.let {it1->
                    LogHelper.d(TAG, "cameraSize width:${cameraSize.width}, height:${cameraSize.height}")
                    parameters.setPreviewSize(cameraSize.width, cameraSize.height)
                    it.parameters = parameters
                    it.setPreviewDisplay(mViewBinding.surfaceView.holder)
                    it.setDisplayOrientation(90)
                    it.startPreview()
                    it.cancelAutoFocus()
                }?:let {
                    LogHelper.d(TAG, "cameraSize 为空")
                }


//                preSize?.let {
//                    //重新定义宽和高,宽始终小于高
//                    val previewWidth = Math.min(preSize.width, preSize.height)
//                    val previewHeight = Math.max(preSize.width, preSize.height)
//                    val scale = previewWidth * 1f / previewHeight
////                    if(width > previewWidth){
////                        width = (width/scale).toInt()
////                    } else if (width < previewWidth){
////                        height = (height*scale).toInt()
////                    }
//                    LogHelper.d(TAG, "最终的尺寸：width:${width},height:${height}")
//                    parameters.setPreviewSize(preSize.width, preSize.height)
//                }


            }
        }

    }

    /**
     * 获取最合适的相机预览尺寸
     */
    private fun getSuitableSize(
        width: Int,
        height: Int,
        parameters: Camera.Parameters
    ): Camera.Size? {
        LogHelper.d(TAG, "想要的尺寸：width:${width}, height:${height}")
        var minDelta = Int.MAX_VALUE
        var index = 0
        val sizes = parameters.supportedPreviewSizes
        for (i in 0..(sizes.size - 1)) {
            val previewSize = sizes[i]
            LogHelper.i(
                TAG,
                "SupportedPreviewSize, width:${previewSize.width}, height:${previewSize.height}"
            )
            val delta = Math.abs(width.minus(previewSize.width))
            if (delta == 0) {
                LogHelper.i(
                    TAG,
                    "最合适的尺寸, width:${previewSize.width}, height:${previewSize.height}"
                )
                return previewSize
            } else {
                if (minDelta > delta) {
                    minDelta = delta
                    index = i
                }
            }
        }
        LogHelper.i(
            TAG,
            "最合适的尺寸, width:${sizes[index].width}, height:${sizes[index].height}"
        )
        return sizes[index]
    }

    private fun getRealScreenMetrics(): Point {
        val size = Point()
        try {
            val display = windowManager.defaultDisplay
            val displayMetrics = DisplayMetrics()
            display.getMetrics(displayMetrics)
            display.getRealSize(size)
            LogHelper.d(TAG, "手机的真实高度：${size.y}, 真实宽度：${size.x}")
        } catch (e: Exception) {
            LogHelper.e(TAG, "getRealScreenMetrics-Exception:${e.message}")
        }
        return size
    }

    private fun getBestCameraResolution(parameters: Camera.Parameters, screenResolution: Point):Camera.Size? {
        var tmp = 0f
        var mindiff = 100f
        val x_d_y = screenResolution.x / screenResolution.y.toFloat()
        var best: Camera.Size? = null
        val supportedPreviewSizes = parameters.supportedPreviewSizes
        for (s in supportedPreviewSizes){
            tmp = Math.abs(s.height.toFloat()/s.width - x_d_y)
            if(tmp < mindiff){
                mindiff = tmp
                best = s
            }
        }
        return best
    }
    //endregion
}